package group.rober.auth.tags;

import freemarker.core.Environment;
import freemarker.template.*;
import group.rober.auth.entity.User;
import group.rober.auth.holder.AuthHolder;
import group.rober.auth.service.AuthService;
import group.rober.saber.holder.ApplicationContextHolder;
import group.rober.saber.kit.StringKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class UserTag implements TemplateDirectiveModel{
//    @Autowired
//    AuthService authService;
//
//    public AuthService getAuthService() {
//        return authService;
//    }
//
//    public void setAuthService(AuthService authService) {
//        this.authService = authService;
//    }

    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        Writer out = env.getOut();

        //将模版里的数字参数转化成int类型的方法，，其它类型的转换请看freemarker文档
        TemplateModel paramValue = (TemplateModel) params.get("userId");
        if(paramValue instanceof SimpleScalar){
            String userId = ((SimpleScalar)paramValue).getAsString();
            if(StringKit.isNotBlank(userId)){
                AuthService authService = ApplicationContextHolder.getBean(AuthService.class);
                User user = authService.getUser(userId);
                if(user!=null){
                    out.write(user.getName());
                }
            }
        }
//        int num = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
//        User user = AuthHolder.getUser();
//        out.write("这是一段文字");

        if (body != null) {
            body.render(env.getOut());
        }
    }
}
